#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <sstream>
#include <algorithm>

using std::cout;
using std::endl;
using std::string;
using std::vector;
using std::ifstream;
using std::ofstream;
using std::istringstream;

struct Record
{
    Record(const string &word, int frequence)
    : _word(word)
    , _frequency(frequence)
    {

    }
	string _word;
	int _frequency;
};

bool operator<(const Record &lhs, const Record &rhs)
{
    return lhs._word < rhs._word;
}

class Dictionary
{
public:
    //读圣经文件，将里面的单词一个个都做处理，并计算出现的次数
    //然后将结果存在vector里面
    void read(const string &filename);

    //遍历vector，然后将vector中的数据写到另外的一个文件中
    void store(const string &filename);
private:
    string dealWord(const string &word);
    void insert(const string &word);
private:
	vector<Record> _dict;
};

void Dictionary::read(const string &filename)
{
    ifstream ifs(filename);//FILE *fp = fopen()
    if(!ifs.good())
    {
        std::cerr << "open file " << filename << " error!" << endl;
        return;
    }

    string line;
    while(getline(ifs, line))
    /* while(ifs >> line) */
    {
        istringstream iss(line);

        string word;
        while(iss >> word, !iss.eof())//iss == bool
        {
            //word是不是合格的，符合要求的单词呢
            //hello! [abd] 
            //dealWord的目的就是想将老的单词转换成符合要求，存到
            //vector中的合格单词
            string newWord = dealWord(word);
            //新单词newWord需要存到vector
            insert(newWord);
        }
    }

    //需要将两个Record进行比较
    sort(_dict.begin(), _dict.end());

    ifs.close();
}

void Dictionary::store(const string &filename)
{
    ofstream ofs(filename);
    if(!ofs.good())
    {
        std::cerr << "ofstream open  file " << filename << " error!" << endl;
        return;
    }

    for(size_t idx = 0; idx != _dict.size(); ++idx)
    {
        ofs << _dict[idx]._word << "        " 
            << _dict[idx]._frequency << endl;
    }

    ofs.close();

}

string Dictionary::dealWord(const string &word)
{
    for(size_t idx = 0; idx != word.size(); ++idx)
    {
        /* if(word[idx] >= 'A' && word[idx] <= 'Z') */
        if(!isalpha(word[idx]))
        {
            return string();//临时对象
        }
    }

    return word;
}

void Dictionary::insert(const string &word)
{
    if(word == string())
    {
        return;
    }

    //合格的word就需要插入到vector
    size_t idx = 0;
    for(idx = 0; idx != _dict.size(); ++idx)
    {
        if(word == _dict[idx]._word)
        {
            ++_dict[idx]._frequency;
            break;
        }
    }

    if(idx == _dict.size())
    {
        _dict.push_back(Record(word, 1));
    }
}

int main(int argc, char **argv)
{
    Dictionary dictionary;
    dictionary.read("The_Holy_Bible.txt");
    dictionary.store("wd.dat");
    
    return 0;
}

